package com.book.bookmanage.advice;

import com.book.bookmanage.config.execption.CustomException;
import com.book.bookmanage.constant.ResponseEnum;
import com.book.bookmanage.utils.Result;
import org.apache.ibatis.annotations.Results;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHandlerAdvice {

    @ExceptionHandler(CustomException.class)
    public Result handleCustomException(CustomException customException) {
        System.out.println("捕获 CustomException 异常信息" + customException.toString());
        return Result.fail(customException);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumenuNotValidExceptionHandler(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        if(bindingResult.hasFieldErrors()) {
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            List<String> errors = new ArrayList<>(fieldErrors.size());
            for (FieldError error : fieldErrors) {
                errors.add(error.getField() + ":" + error.getDefaultMessage());
            }
            return Result.fail(ResponseEnum.PARAM_ERROR, errors.toString());
        }
        return Result.fail(ResponseEnum.PARAM_ERROR, ResponseEnum.FAIL);
    }
}
